package cn.enjoy.tool.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.util.HashSet;

/**
 * 雪花算法工具
 * <p>
 * 核心代码：
 * timestampLeftShift     （workIdBits + dataCenterIdBits）      sequenceBits
 * 毫秒级时间戳位 41位               + 工作进程位 10位             + 毫秒内序列号位 12位
 *
 * @author K
 * @date 2023/10/24 10:19
 */
@Slf4j
public class SnowflakeUtil {
    /**
     * 开始时间截 (2023-10-24)
     */
    private final long twepoch = 1609944039799L;
    /**
     * 工作进程位-机器Id所占的位数
     */
    private final long workerIdBits = 8L;
    /**
     * 工作进程位-数据中心Id所占的位数
     */
    private final long dataCenterIdBits = 2L;
    /**
     * 支持的最大机器id = 2^workerIdBits
     */
    private final long maxWorkerId = ~(-1L << workerIdBits);
    /**
     * 支持的最大数据标识id = 2^dataCenterIdBits
     */
    private final long maxDataCenterId = ~(-1L << dataCenterIdBits);
    /**
     * 毫秒内序列号所占的位数
     */
    private final long sequenceBits = 12L;
    /**
     * 机器ID向左移12位
     */
    private final long workerIdShift = sequenceBits;
    /**
     * 数据标识id向左移17位(12+5)
     */
    private final long dataCenterIdShift = sequenceBits + workerIdBits;
    /**
     * 时间截向左移22位(12+5+5)
     */
    private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
    /**
     * 生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095)
     */
    private final long sequenceMask = ~(-1L << sequenceBits);
    /**
     * 工作机器ID(0~1024)
     */
    private long workerId;
    /**
     * 数据中心ID(0~1024)
     */
    private long dataCenterId;
    /**
     * 毫秒内序列(0~4095)
     */
    private long sequence = 0L;
    /**
     * 上次生成ID的时间截
     */
    private long lastTimestamp = -1L;
    /**
     * 实例
     */
    private static final SnowflakeUtil INSTANCE = new SnowflakeUtil();


    public SnowflakeUtil() {
        long workerId = getWorkerId();
        long dataCenterId = getDataCenterId();
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("workerId can't be greater than %d or less than 0", maxWorkerId));
        }
        if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("dataCenterId can't be greater than %d or less than 0", maxDataCenterId));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    /**
     * 获得下一个ID
     */
    public static long getId() {
        return INSTANCE.nextId();
    }

    /**
     * 获得下一个ID (该方法是线程安全的)
     */
    private synchronized Long nextId() {
        long timestamp = timeGen();

        //如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            try {
                throw new RuntimeException(
                        String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }

        //如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            //时间戳改变，毫秒内序列重置
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //移位并通过或运算拼到一起组成64位的ID
        long id = ((timestamp - twepoch) << timestampLeftShift)
                | (dataCenterId << dataCenterIdShift)
                | (workerId << workerIdShift)
                | sequence;

        log.info("id:{}, timestamp:{}, timestampLeftShift:{}, dataCenterId:{}, workId:{}, sequence:{}",
                id, timestamp, timestampLeftShift, dataCenterId, workerId, sequence);

        return id;
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     *
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     *
     * @return 当前时间(毫秒)
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }


    private long getWorkerId() {
        try {
            StringBuilder ipStr = new StringBuilder();
            String curIpAddress = InetAddress.getLocalHost().getHostAddress();
            String[] str = curIpAddress.split("\\.");
            for (String s : str) {
                ipStr.append(s);
            }
            long ipNumber = Long.parseLong(ipStr.toString());
            return ipNumber % maxWorkerId;
        } catch (Exception e) {
            log.error("work get local Host Address failed:", e);
            return RandomUtils.nextLong(0, maxDataCenterId);
        }
    }

    private long getDataCenterId() {
        try {
            int sum = 0;
            String curIpAddress = InetAddress.getLocalHost().getHostAddress();
            int[] ints = StringUtils.toCodePoints(curIpAddress);
            for (int b : ints) {
                sum += b;
            }
            return sum % maxDataCenterId;
        } catch (Exception e) {
            log.error("dataCenter get local Host Address failed:", e);
            return RandomUtils.nextLong(0, maxDataCenterId);
        }
    }

    public static void main(String[] args) {
        HashSet<Long> hashSet = new HashSet<>();
        for (int i = 0; i < 10000; i++) {
            hashSet.add(getId());
        }
        System.out.println();
    }

}
